var express = require('express');
var router = express.Router();

var path = require('path');
var CONFIG = require('../../common/config');
var CODE = require('../../common/code');
var FileDownLoader = require('../../common/util/FileDownLoader');
var FileUpLoader = require('../../common/util/FileUpLoader');
var FileUtil = require('../../common/util/FileUtil');
var CommonUtil = require('../../common/util/CommonUtil');
var rpcFunc=require('./../routes/rpcSrv/rpcFunc.js');
var CODE = require('../../common/code');
var tg3Util = require('./util/tg3Util');
var checkUtil = require('./util/checkUtil');
var StaticizeUtil = require('../../common/util/StaticizeUtil');
var async = require( 'async'); // 同步控制

//------------------------------------------------------------------
/**
 * 接口名称:getContourOfTexts
 * 参数：device
 * 参数：uuid
 * 参数：texts,string类型，本页文字属性列表的JSON，例如：
 *          "[{id:1,fz:64,te:\"xyz\":style:{ v:1,fn:微软雅黑,fs:20,bi:0,po:1,vpo:2,cs:6,ls:10,td:0} }]"
 * 返回结果：
 * {
 *     "success":1,
 *     "msg":"成功",
 *     "data":{
 *         "texts":"[{\"id\":3,\"cp\":[]}]"
 *     }
 * }
 */
function getContourOfTexts(req, res, next) {
    var url = req.query.url || req.body.url;
    var user_id =Number( req.query.user_id || req.body.user_id ||0);
    var texts = req.query.texts || req.body.texts;

    // return function
    function ret_func_json(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }
    if(typeof texts=='undefined' || texts == null || texts.trim().length == 0){
        return ret_func_json(0,CODE.TEXT_PARA_EMPTY, {});
    }

    rpcFunc.contourOfTexts(texts,function(error, ret){
        if(error){
            return ret_func_json(0,CODE.OPERATION_FAILED,{});
        }
        return ret_func_json(1,CODE.OPERATION_SUCCESS,{"texts":ret});
    })
}
router.get('/getContourOfTexts', getContourOfTexts);
router.post('/getContourOfTexts', getContourOfTexts);

/**
 * 获取设计模板文字轮廓信息
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3 标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: designId	模板唯一标识
 * 参数: typeL	一级分类标识
 *
 * 测试地址: http://localhost:3000/font/getDesignContour_v5_7?designId=512&device=1&typeL=1
 * */
function getDesignContour_v5_7(req, res, next) {

    var designId = checkUtil.numberFromReq(req, "designId") || 0;
    var typeL = checkUtil.numberFromReq(req, "typeL") || 0;
    if(designId <= 0) {
        return tg3Util.ret_func_json(0, '参数错误', {}, res);
    }

    var uri = 'getDesignContour_v5_7';
    var para = {
        designId : designId
    };

    // 先从 redis 获取缓存, 若存在, 则直接返回, 不存在, 获取并设置缓存
    StaticizeUtil.getByRedis(__filename, uri, para, function(error, content){
        if(content){
            return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS,{"texts":content}, res);
        }

        // 1. 根据 designId 获取模板各页轮廓索引信息
        tg3Util.getTextInfoByDesignId(designId, function(textErr, texts){

            if(textErr) {
                console.log("font.js [getDesignContour_v5_7] getTextInfoByDesignId err: "+ textErr);
                return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{}, res);
            }

            // 2. 准备获取各页文字轮廓信息的方法数组
            var asynFuncs = [];
            for(var i=0; i < texts.length; i++) {
                asynFuncs.push((function(index, text){

                    var obj = {pageIndex : i};

                    return function(asyncCallback) {
                        text = JSON.stringify(text);
                        rpcFunc.contourOfTexts(text,function(error, ret){
                            obj.contours = ret;
                            asyncCallback(error, obj);
                        });
                    }
                })(i, texts[i]));
            }
            // 3. 异步取得所有页轮廓信息
            async.parallel(asynFuncs, function(asyErr, result){
                if(asyErr) {
                    console.log('font [getDesignContour_v5_7] contourOfTexts err: ' + asyErr);
                    return tg3Util.ret_func_json(0,CODE.OPERATION_FAILED,{}, res);
                }
                var content = StaticizeUtil.recordByRedis(__filename, uri, para, result);  // 缓存
                return tg3Util.ret_func_json(1,CODE.OPERATION_SUCCESS,{"texts":content}, res);
            });
        });
    });
}
router.get('/getDesignContour_v5_7', getDesignContour_v5_7);
router.post('/getDesignContour_v5_7', getDesignContour_v5_7);




module.exports = router;
